<?php

namespace Admin\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\TableGateway;
use Library\String;

class ProductModel {

    const table_product = 'zend_product';
    const table_category = 'zend_product_category';
    const table_maker = 'zend_product_maker';
    const table_category_maker = 'zend_category_maker';

    private $adapter;
    private $productGateway;
    private $categoryGateway;
    private $makerGateway;
    private $rltCategoryMaker;

    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
        $this->productGateway = new TableGateway(self::table_product, $this->adapter);
        $this->categoryGateway = new TableGateway(self::table_category, $this->adapter);
        $this->makerGateway = new TableGateway(self::table_maker, $this->adapter);
        $this->rltCategoryMaker = new TableGateway(self::table_category_maker, $this->adapter);
    }

    public function getListProduct($aryConditions) {
        if (!$aryConditions['current_page']) {
            $aryConditions['current_page'] = 1;
        }
        $select = $this->productGateway->getSql()->select();
        $select->columns(array(
            'product_id',
            'product_name',
            'product_image',
            'product_name_filter',
            'product_price',
            'product_type',
            'product_category_id',
            'product_price_sale_of'
        ));
        $select->join(self::table_category, 'product_category_id = category_id', array('category_name', 'category_name_filter'));
        $select->join(self::table_maker, 'product_maker_maker_id = product_maker_id', array('product_maker_name'));
        $select->where(array('product_del_flag = ? ' => 0));

        if ($aryConditions['category_id'] && is_numeric($aryConditions['category_id'])) {
            $select->where(array('product_category_id = ? ' => $aryConditions['category_id']));
        }
        $select->order(array('product_update_date' => 'DESC'));

        $paginatorAdapter = new \Zend\Paginator\Adapter\DbSelect($select, $this->adapter);

        $paginator = new \Zend\Paginator\Paginator($paginatorAdapter);

        $paginator->setCurrentPageNumber($aryConditions['current_page']);

        $paginator->setItemCountPerPage($aryConditions['record_per_page']);

        //$result = $this->productGateway->selectWith($select);
        //return $result->toArray();
        return $paginator;
    }

    public function saveProduct($aryData) {
        $aryProductData = array();
        $aryProductData['product_name'] = $aryData['product_name'];
        $aryProductData['product_name_filter'] = String::filterUnicode($aryData['product_name']);
        $aryProductData['product_name_search'] = String::encodingUnicode($aryData['product_name']);
        if ($aryData['product_image']['name']) {
            $aryProductData['product_image'] = $aryData['product_image']['name'];
        }
        $aryProductData['product_price'] = $aryData['product_price'];
        $aryProductData['product_price_sale_of'] = $aryData['product_price_sale_of'];
        $aryProductData['product_type'] = $aryData['product_type'];
        $aryProductData['product_category_id'] = $aryData['product_category_id'];
        $aryProductData['product_category_name'] = $aryData['product_category_name'];
        $aryProductData['product_maker_maker_id'] = $aryData['product_maker_maker_id'];
        $aryProductData['product_maker_maker_name'] = $aryData['product_maker_maker_name'];
        $aryProductData['product_maker_maker_name_filter'] = String::filterUnicode($aryData['product_maker_maker_name']);
        $aryProductData['product_content_detail'] = $aryData['product_content_detail'];

        if ($aryData['action_type'] == 'add') {
            $aryProductData['product_create_date'] = date('Y-m-d H:i:s');
            $aryProductData['product_update_date'] = date('Y-m-d H:i:s');
            $result = $this->productGateway->insert($aryProductData);
        } else {
            $aryProductData['product_update_date'] = date('Y-m-d H:i:s');
            $result = $this->productGateway->update($aryProductData, array('product_id' => (int) $aryData['product_id']));
        }
        return $result;
    }

    public function deleteProduct($productId) {
        $result = $this->productGateway->update(array('product_del_flag' => 1), array('product_id' => (int) $productId));
        return $result;
    }

    public function getCategoryOptions() {
        $select = $this->categoryGateway->getSql()->select();
        $select->columns(array('category_id', 'category_name'));
        $select->where(array('category_del_flag = ?' => 0));
        $result = $this->categoryGateway->selectWith($select);
        $data = $result->toArray();
        $aryOptions = array();
        foreach ($data as $option) {
            $aryOptions[$option['category_id']] = $option['category_name'];
        }
        return $aryOptions;
    }

    public function getMakerOption() {
        $select = $this->makerGateway->getSql()->select();
        $select->columns(array('product_maker_id', 'product_maker_name'));
        $select->where(array('product_maker_del_flag = ? ' => 0));
        $result = $this->makerGateway->selectWith($select);
        $aryData = $result->toArray();
        $makerOption = array();
        foreach ($aryData as $option) {
            $makerOption[$option['product_maker_id']] = $option['product_maker_name'];
        }
        return $makerOption;
    }

    public function getProductById($productId) {
        $select = $this->productGateway->getSql()->select();
        $select->columns(array(
            'product_id',
            'product_name',
            'product_price',
            'product_price_sale_of',
            'product_type',
            'product_category_id',
            'product_maker_maker_id',
            'product_spec_content',
            'product_content_detail',
            'product_category_name',
            'product_maker_maker_name'
        ));
        $select->where(array('product_id = ? ' => (int) $productId));
        $result = $this->productGateway->selectWith($select);
        return $result->current();
    }

    public function getListCategory() {
        $select = $this->categoryGateway->getSql()->select();
        $select->columns(array('category_id', 'category_name', 'category_image', 'category_parent'));
        $select->where(array('category_del_flag = ? ' => 0));
        $select->order(array('category_order' => 'ASC'));
        $result = $this->categoryGateway->selectWith($select);
        return $result->toArray();
    }

    public function saveCategory($aryData) {
        $aryCategory = array();
        $aryCategory['category_name'] = $aryData['category_name'];
        $aryCategory['category_name_filter'] = String::filterUnicode($aryData['category_name']);
        if ($aryData['category_image']['name']) {
            $aryCategory['category_image'] = $aryData['category_image']['name'];
        }
        if ($aryData['category_parent']) {
            $aryCategory['category_parent'] = $aryData['category_parent'];
        } else {
            $aryCategory['category_parent'] = 0;
        }
        if ($aryData['category_meta_title']) {
            $aryCategory['category_meta_title'] = $aryData['category_meta_title'];
        }
        if ($aryData['category_meta_keyword']) {
            $aryCategory['category_meta_keyword'] = $aryData['category_meta_keyword'];
        }
        if ($aryData['category_meta_description']) {
            $aryCategory['category_meta_description'] = $aryData['category_meta_description'];
        }
        if ($aryData['action_type'] == 'add') {
            $result = $this->categoryGateway->insert($aryCategory);
            $returnCategoryId = $this->categoryGateway->getLastInsertValue();
        } else {
            //update table category
            $result = $this->categoryGateway->update($aryCategory, array('category_id = ? ' => $aryData['category_id']));
            $returnCategoryId = $aryData['category_id'];
            //reupdate category in product table
            if ($this->_checkExistCategoryInProduct($returnCategoryId)) {
                $aryProduct = array();
                $aryProduct['product_category_name'] = $aryData['category_name'];
                $aryProduct['product_category_name_filter'] = String::filterUnicode($aryData['category_name']);
                $result = $this->productGateway->update($aryProduct, array('product_category_id' => $returnCategoryId));
            }
        }
        //delete existed maker in relation category-maker table
        if ($this->_checkExistRelationMaker($returnCategoryId)) {
            $result = $this->rltCategoryMaker->delete(array('relation_category_id = ?' => $returnCategoryId));
        }
        //re insert maker in to relation category-maker table
        if ($result) {
            foreach ($aryData['relation_maker_id'] as $key => $makerId) {
                $aryRltData = array();
                $aryRltData['relation_category_id'] = $returnCategoryId;
                $aryRltData['relation_maker_id'] = $makerId;
                $result = $this->rltCategoryMaker->insert($aryRltData);
            }
        }
        return $result;
    }

    public function _checkExistCategoryInProduct($categoryId) {
        $select = $this->productGateway->getSql()->select()
                ->columns(array('product_category_id'))
                ->where(array('product_category_id' => $categoryId));
        $result = $this->productGateway->selectWith($select);
        $data = $result->toArray();
        if (isset($data[0])) {
            return true;
        }
        return false;
    }

    public function _checkExistRelationMaker($categoryId) {
        $select = $this->rltCategoryMaker->getSql()->select()
                ->columns(array('relation_category_id'))
                ->where(array('relation_category_id' => $categoryId));
        $result = $this->rltCategoryMaker->selectWith($select);
        $data = $result->toArray();
        if (isset($data[0])) {
            return true;
        }
        return false;
    }

    public function getCategoryById($categoryId) {

        $select = $this->categoryGateway->getSql()->select();
        $select->columns(array(
            'category_id',
            'category_name',
            'category_parent',
            'category_meta_title',
            'category_meta_keyword',
            'category_meta_description'));

        $select->where(array('category_id = ? ' => $categoryId));

        $result = $this->categoryGateway->selectWith($select);

        return $result->current();
    }

    public function deleteCategory($categoryId) {
        $result = $this->categoryGateway->update(array('category_del_flag' => 1), array('category_id = ?' => $categoryId));
        if ($result) {
            $this->productGateway->update(array('product_del_flag' => 1), array('product_category_id' => $categoryId));
            $this->rltCategoryMaker->delete(array('relation_category_id' => $categoryId));
        }
        return $result;
    }

    public function getProductMaker() {
        $select = $this->makerGateway->getSql()->select();
        $select->columns(array('product_maker_id', 'product_maker_name'));
        $select->where(array('product_maker_del_flag = ?' => 0));
        $result = $this->makerGateway->selectWith($select);
        return $result->toArray();
    }

    public function saveMaker($aryData) {
        $aryMaker = array();
        $aryMaker['product_maker_name'] = $aryData['product_maker_name'];
        $aryMaker['product_maker_name_filter'] = String::filterUnicode($aryData['product_maker_name']);
        if ($aryData['action_type'] == 'add') {
            $result = $this->makerGateway->insert($aryMaker);
        } else {
            $result = $this->makerGateway->update($aryMaker, array('product_maker_id = ?' => $aryData['product_maker_id']));
            if ($result && $this->_checkExistMakerInProduct($aryData['product_maker_id'])) {
                $aryProduct = array();
                $aryProduct['product_maker_maker_name'] = $aryData['product_maker_name'];
                $aryProduct['product_maker_maker_name_filter'] = String::filterUnicode($aryData['product_maker_name']);
                $result = $this->productGateway->update($aryProduct, array('product_maker_maker_id = ?' => $aryData['product_maker_id']));
            }
        }
        return $result;
    }

    public function _checkExistMakerInProduct($makerId) {
        $select = $this->productGateway->getSql()->select()->columns(array('product_maker_maker_id'));
        $select->where(array('product_maker_maker_id = ?' => $makerId));
        $result = $this->productGateway->selectWith($select);
        $data = $result->toArray();
        if (isset($data[0])) {
            return true;
        }
        return false;
    }

    public function getMakerById($makerId) {
        $select = $this->makerGateway->getSql()->select();
        $select->columns(array('product_maker_id', 'product_maker_name'));
        $select->where(array('product_maker_del_flag = ?' => 0));
        $select->where(array('product_maker_id = ?' => $makerId));
        $result = $this->makerGateway->selectWith($select);
        return $result->current();
    }

    public function deleteMaker($makerId) {
        $result = $this->makerGateway->update(array('product_maker_del_flag' => 1), array('product_maker_id = ?' => $makerId));
        if ($result && $this->_checkExistMakerInProduct($makerId)) {
            $result = $this->productGateway->update(array('product_del_flag' => 1), array('product_maker_maker_id = ?' => $makerId));
        }
        if ($this->_checkExistMakerInRelation($makerId)) {
            $result = $this->rltCategoryMaker->delete(array('relation_maker_id = ?' => $makerId));
        }
        return $result;
    }

    public function _checkExistMakerInRelation($makerId) {
        $select = $this->rltCategoryMaker->getSql()->select()
                ->columns(array('relation_maker_id'))
                ->where(array('relation_maker_id' => $makerId));
        $result = $this->rltCategoryMaker->selectWith($select);
        $data = $result->toArray();
        if (isset($data[0])) {
            return true;
        }
        return false;
    }

    public function getMakerByCategoryId($categoryId) {
        $select = $this->rltCategoryMaker->getSql()->select()
                ->columns(array('relation_maker_id'));

        $select->join(self::table_maker, 'relation_maker_id = product_maker_id', array(), \Zend\Db\Sql\Select::JOIN_LEFT);

        $select->where(array('relation_category_id = ?' => $categoryId));

        $result = $this->rltCategoryMaker->selectWith($select);

        $aryMaker = $result->toArray();

        $makerChecked = array();

        foreach ($aryMaker as $maker) {
            $makerChecked[] = $maker['relation_maker_id'];
        }
        return $makerChecked;
    }

}
